package com.family.gmall.common.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Auther: family
 * @Date: 2023/8/6 18:07
 * @Description:
 */
@Component
@Slf4j
public class MQProducerAckConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        //指定ConfirmCallback
        rabbitTemplate.setConfirmCallback(this);
        //指定ReturnCallback
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("消息发送成功：" + JSON.toJSONString(correlationData));
        } else {
            log.info("消息发送失败：" + cause + "数据：" + JSON.toJSONString(correlationData));
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        //反序列化对象输出
        System.out.println("消息主体：" + new String(message.getBody()));
        System.out.println("应答码：" + replyCode);
        System.out.println("描述：" + replyText);
        System.out.println("消息使用的交换机exchange：" + exchange);
        System.out.println("消息使用的路由键routing：" + routingKey);
    }
}
